﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DataMappers
{
    public class UnitOfWork
    {
    private ClassDataMappers _classMapper = new ClassDataMappers();
	private readonly Connection _conn;
	
	public UnitOfWork(Connection connector){
		_conn = connector;
	}
	public IEntityMapper<K, DT> Get<K, DT>(DT obj)  where DT : IDomainObject<K, DT>
    {
		return _classMapper.Get<K,DT>(obj);
	}

    public IEntityMapper<K, DT> Get<K, DT>(Type t)  where DT : IDomainObject<K, DT>
    {
        return _classMapper.Get<K, DT>(t);
    }

    public UnitOfWork WithEntityMapper<K, T>(Type t, IEntityMapper<K, T> dm) where T : IDomainObject< K, T>
    {
        dm.SetConnector(_conn);
        _classMapper.add<K,T>(t, dm);
        return this;
	}
	
	public void Save(){
        foreach (IEntityMapperForUpdates dm in _classMapper.getAllMappersInReverseOrder())
        {
            dm.DeleteRemovedObjects();
        }
        foreach (IEntityMapperForUpdates dm in _classMapper.getAllMappers())
        {
            dm.InsertNewObjects();
        }
        foreach (IEntityMapperForUpdates dm in _classMapper.getAllMappers())
        {
            dm.UpdateDirtyObjects();
        }
       
	}
	
	private static UnitOfWork _current;
    //public static void SetCurrent(UnitOfWork uow) {
    //    _current = uow;
    //}    
    public static UnitOfWork Current {
        get { return _current; }
        set { _current = value; }
    }

    public void Refresh()
    {
        foreach (IEntityMapperForUpdates dm in _classMapper.getAllMappers())
        {
            dm.Refresh();
        }
    }

    public void DeleteAllObjects()
    {
        foreach (IEntityMapperForUpdates dm in _classMapper.getAllMappers())
        {
            dm.DeleteAllObjects();
        }
        UnitOfWork.Current.Save();
    }
    }
}
